﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MebAppMarketplace
{
    public static class ControllerExtension
    {
        public static RedirectResult RedirectToReturnUrl(this Controller controller)
        {
            return controller.Redirect(controller.Request.Query["returnUrl"]);
        }
        /// <summary>
        /// 将ModelState中的第一条错误写入到指定名称的ViewData
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="viewDataName"></param>
        public static void ViewDataErrorFromModelState(this Controller controller, string viewDataName)
        {
            var errorList = controller.ModelState.Values.SelectMany(m => m.Errors)
                                 .Select(e => e.ErrorMessage)
                                 .ToList();
            controller.ViewData[viewDataName] = errorList.First();
        }
        public static IActionResult ViewError(this Controller controller, string viewDataName = "ActionError")
        {
            var errorList = controller.ModelState.Values.SelectMany(m => m.Errors)
                                 .Select(e => e.ErrorMessage)
                                 .ToList();
            controller.ViewData[viewDataName] = errorList.First();
            return controller.View();
        }
        /// <summary>
        /// 返回ModelState中的第一条错误
        /// </summary>
        /// <param name="controller"></param>
        /// <returns></returns>
        public static JsonResult JsonErrorFromModelState(this Controller controller)
        {
            var errorList = controller.ModelState.Values.SelectMany(m => m.Errors)
                                 .Select(e => e.ErrorMessage)
                                 .ToList();
            return controller.JsonError(errorList.First());
        }
        /// <summary>
        /// 返回一个格式为{ code = 400, msg = "错误请求" }的JSON对象
        /// </summary>
        /// <param name="controller"></param>
        /// <returns></returns>
        public static JsonResult JsonBadRequest(this Controller controller)
        {
            return controller.Json(new { code = 400, msg = "错误请求" });
        }

        /// <summary>
        /// 返回一个格式为{ code = 10010, msg = "同名资源已存在" }的JSON对象
        /// </summary>
        /// <param name="controller"></param>
        /// <returns></returns>
        public static JsonResult JsonDuplicate(this Controller controller)
        {
            return controller.Json(new { code = 10010, msg = "同名资源已存在" });
        }

        /// <summary>
        /// 返回一个格式为{ code = 404, msg = "无效资源" }的JSON对象
        /// </summary>
        /// <param name="controller"></param>
        /// <returns></returns>
        public static JsonResult JsonNotFound(this Controller controller)
        {
            return controller.Json(new { code = 404, msg = "无效资源" });
        }

        /// <summary>
        /// 返回一个格式为{ code = 200, msg = "操作成功" }的对象
        /// </summary>
        /// <param name="controller"></param>
        /// <returns></returns>
        public static JsonResult JsonOk(this Controller controller)
        {
            return controller.Json(new { code = 200, msg = "操作成功" });
        }

        /// <summary>
        /// 返回一个格式为{ code = 200, msg = "操作成功", data = data }的对象
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static JsonResult JsonOk(this Controller controller, object data)
        {
            return controller.Json(new { code = 200, msg = "操作成功", data = data });
        }

        /// <summary>
        /// 返回一个格式为{ code = 200, msg = msg }的JSON对象
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static JsonResult JsonOk(this Controller controller, string msg)
        {
            return controller.Json(new { code = 200, msg = msg });
        }

        /// <summary>
        /// 返回一个格式为{ code = 200, msg = msg, data = data }的JSON对象
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="data"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static JsonResult JsonOk(this Controller controller, object data, string msg = "操作成功")
        {
            return controller.Json(new { code = 200, msg = msg, data = data });
        }

        /// <summary>
        /// 返回一个格式为{ code = 500, msg = msg }的JSON对象
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static JsonResult JsonError(this Controller controller, string msg)
        {
            return controller.Json(new { code = 500, msg = msg });
        }

        /// <summary>
        /// 返回一个格式为{ code = 500, msg = msg, data = data }的JSON对象
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="msg"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static JsonResult JsonError(this Controller controller, string msg, object data)
        {
            return controller.Json(new { code = 500, msg = msg, data = data });
        }

        /// <summary>
        /// 将一个上传的文件流写入到一个临时文件
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="file"></param>
        /// <returns>临时文件绝对路径</returns>
        public static string WriteAsTempFile(this Controller controller, IFormFile file)
        {
            var tempFile = Path.GetTempFileName();
            using (var tempFileStream = File.Open(tempFile, FileMode.Open))
            {
                file.CopyTo(tempFileStream);
            }
            return tempFile;
        }

        /// <summary>
        /// 断点下载
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="fullpath"></param>
        /// <returns>是否新的下载</returns>
        public static async Task<bool> RangeDownload(this Controller controller, string fullpath)
        {
            long size, start, end, length, fp = 0;
            using (StreamReader reader = new StreamReader(File.OpenRead(fullpath)))
            {
                size = reader.BaseStream.Length;
                start = 0;
                end = size - 1;
                length = size;
                // Now that we've gotten so far without errors we send the accept range header
                /* At the moment we only support single ranges.
                 * Multiple ranges requires some more work to ensure it works correctly
                 * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
                 *
                 * Multirange support annouces itself with:
                 * header('Accept-Ranges: bytes');
                 *
                 * Multirange content must be sent with multipart/byteranges mediatype,
                 * (mediatype = mimetype)
                 * as well as a boundry header to indicate the various chunks of data.
                 */
                controller.Response.Headers.Add("Accept-Ranges", "0-" + size);
                // header('Accept-Ranges: bytes');
                // multipart/byteranges
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2

                if (!String.IsNullOrEmpty(controller.Request.Headers["HTTP_RANGE"]))
                {
                    long anotherStart = start;
                    long anotherEnd = end;
                    string[] arr_split = controller.Request.Headers["HTTP_RANGE"].FirstOrDefault().Split(new char[] { Convert.ToChar("=") });
                    string range = arr_split[1];

                    // Make sure the client hasn't sent us a multibyte range
                    if (range.IndexOf(",") > -1)
                    {
                        // (?) Shoud this be issued here, or should the first
                        // range be used? Or should the header be ignored and
                        // we output the whole content?
                        controller.Response.Headers.Add("Content-Range", "bytes " + start + "-" + end + "/" + size);
                        controller.Response.StatusCode = 416;
                        await controller.Response.WriteAsync("Requested Range Not Satisfiable");
                        return false;
                    }
                    else
                    {

                        // If the range starts with an '-' we start from the beginning
                        // If not, we forward the file pointer
                        // And make sure to get the end byte if spesified
                        if (range.StartsWith("-"))
                        {
                            // The n-number of the last bytes is requested
                            anotherStart = size - Convert.ToInt64(range.Substring(1));
                        }
                        else
                        {
                            arr_split = range.Split(new char[] { Convert.ToChar("-") });
                            anotherStart = Convert.ToInt64(arr_split[0]);
                            long temp = 0;
                            anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : size;
                        }
                        /* Check the range and make sure it's treated according to the specs.
                         * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
                         */
                        // End bytes can not be larger than $end.
                        anotherEnd = (anotherEnd > end) ? end : anotherEnd;
                        // Validate the requested range and return an error if it's not correct.
                        if (anotherStart > anotherEnd || anotherStart > size - 1 || anotherEnd >= size)
                        {

                            controller.Response.Headers.Add("Content-Range", "bytes " + start + "-" + end + "/" + size);
                            controller.Response.StatusCode = 416;
                            await controller.Response.WriteAsync("Requested Range Not Satisfiable");
                            return false;
                        }
                        else
                        {
                            start = anotherStart;
                            end = anotherEnd;

                            length = end - start + 1; // Calculate new content length
                            fp = reader.BaseStream.Seek(start, SeekOrigin.Begin);
                            controller.Response.StatusCode = 206;
                        }
                    }
                }
            }
            // Notify the client the byte range we'll be outputting
            controller.Response.Headers.Add("Content-Range", "bytes " + start + "-" + end + "/" + size);
            controller.Response.Headers.Add("Content-Length", length.ToString());
            // Start buffered download
            await controller.Response.SendFileAsync(fullpath, fp, length);
            return start == 0;
        }
    }
}
